﻿$.work = function (action, args) {
    var def = $.Deferred(function (dfd) {
        if (window.Worker) {
            var worker = new Worker('/jsworker');
            worker.addEventListener('message', function (event) {
                //Resolve the Deferred when the Web Worker completes
                def.resolve(event.data);
            }, false);

            worker.addEventListener('error', function (event) {
                //Reject the Deferred if the Web Worker has an error
                def.reject(event);
            }, false);

            //Start the worker
            worker.postMessage({
                action: action.toString(),
                args: args
            });
        } else {
            //If the browser doesn't support workers then execute synchronously.
            //This is done in a setTimeout to give the browser a chance to execute
            //other stuff before starting the hard work.
            setTimeout(function () {
                try {
                    var result = action(args);
                    dfd.resolve(result);
                } catch (e) {
                    dfd.reject(e);
                }
            }, 0);
        }
    });

    //Return the promise to do this work at some point
    return def.promise();
};